package com.hzhk.happyrent.ui.activity.personal;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hzhk.happyrent.R;
import com.hzhk.happyrent.bean.CodeModel;
import com.hzhk.happyrent.bean.login.LoginResponse;
import com.hzhk.happyrent.bean.person.BindModel;
import com.hzhk.happyrent.bean.person.CheckModel;
import com.hzhk.happyrent.network.API;
import com.hzhk.happyrent.network.HttpManager;
import com.hzhk.happyrent.network.MyStringTransResponse;
import com.hzhk.happyrent.ui.fragment.login.LoginFragment;
import com.hzhk.happyrent.ui.fragment.login.RegisterFragment;
import com.hzhk.happyrent.utils.MyPerference;
import com.tamic.novate.Throwable;
import com.umeng.socialize.Config;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.handler.UMWXHandler;
import com.umeng.socialize.utils.SocializeUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends AppCompatActivity implements RegisterFragment.OnFragmentInteractionListener {

    @BindView(R.id.share_login)
    ImageView shareLogin;
    @BindView(R.id.share_register)
    ImageView shareRegister;
    @BindView(R.id.vp_login_or_register)
    ViewPager vpLoginOrRegister;
    @BindView(R.id.title_login)
    TextView titleLogin;
    @BindView(R.id.title_register)
    TextView titleRegister;
    @BindView(R.id.login_wechat)
    ImageView loginWechat;
    private ProgressDialog dialog;
    private Logger log = LoggerFactory.getLogger(this.getClass().getName());
    private String[] fragments = new String[]{
            LoginFragment.class.getName(),
            RegisterFragment.class.getName()
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.umeng_blue));
        }
        dialog = new ProgressDialog(this);
        initView();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UMShareAPI.get(this).release();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        UMShareAPI.get(this).onSaveInstanceState(outState);
    }

    private void initView() {
        vpLoginOrRegister.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setPosition(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        LoginOrRegisterAdapter loginOrRegisterAdapter = new LoginOrRegisterAdapter(getSupportFragmentManager(), this);
        vpLoginOrRegister.setAdapter(loginOrRegisterAdapter);
    }

    @OnClick({R.id.title_login, R.id.title_register, R.id.login_wechat})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_login:
                vpLoginOrRegister.setCurrentItem(0);
                setPosition(0);
                break;
            case R.id.title_register:
                vpLoginOrRegister.setCurrentItem(1);
                setPosition(1);
                break;
            case R.id.login_wechat:
                /*测试数据 start*/
                /*Map<String, String> data =new HashMap<>();
                data.put("uid","oG1Jlv2F9nK1plvMLzwEyf7peZZg");
                data.put("name","Hello World");
                data.put("iconurl","http://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83epicrf8Jo0vHmIQ5PHHg8tucC5s0zxyyZTX7kSTxLIMgdrjWqeWhxVAYVbahhD5Q0ZiaiaIOk6iabjf0g/0");
                initData(data);*/
                /*测试数据 end*/

                /*每次登陆都需要授权*/
                Config.isNeedAuth = true;
               /* UMShareConfig config = new UMShareConfig();
                config.isNeedAuthOnGetUserInfo(true);
                config.isNeedAuthOnGetUserInfo();
                UMShareAPI.get(this).setShareConfig(config);*/
                UMShareAPI.get(this).getPlatformInfo(this, SHARE_MEDIA.WEIXIN, umAuthListener);
                break;
        }
    }

    UMAuthListener umAuthListener = new UMAuthListener() {
        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
            SocializeUtils.safeCloseDialog(dialog);
        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            //SocializeUtils.safeCloseDialog(dialog);
            if (platform == SHARE_MEDIA.WEIXIN && data != null) {
                initData(data);
            }

        }

        @Override
        public void onError(SHARE_MEDIA share_media, int i, java.lang.Throwable throwable) {
            ///SocializeUtils.safeCloseDialog(dialog);
            Toast.makeText(LoginActivity.this, "失败：" + throwable.getMessage(), Toast.LENGTH_LONG).show();
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            //SocializeUtils.safeCloseDialog(dialog);
            Toast.makeText(LoginActivity.this, "取消了", Toast.LENGTH_LONG).show();
        }
    };

    private void initData(Map<String, String> data) {
        String uid = data.get("uid");
        log.debug("open_id=" + uid);
        String name = data.get("name");
        log.debug("nickname=" + name);
        String iconurl = data.get("iconurl");
        log.debug("avatar=" + iconurl);
        Map<String, Object> params = new HashMap<>();
        params.put("open_id", uid);
        params.put("avatar", iconurl);
        params.put("nickname", name);
        HttpManager.getInstance().perform_post(API.WX_LOGIN, params, new MyStringTransResponse(this) {
            @Override
            public void onNext(String response) {
                log.debug("response" + response);
                CodeModel codeModel = new  Gson().fromJson(response, CodeModel.class);
                if (codeModel.getErrCode() == 0) {
                    BindModel bindModel = new Gson().fromJson(response, BindModel.class);
                    log.debug("bindModel.getErrCode() =" + bindModel.getErrCode());
                    if (TextUtils.isEmpty(bindModel.getData().getPhone())) {
                        log.debug("1111111111111");
                        Intent intent = new Intent(LoginActivity.this, BindPhoneActivity.class);
                        intent.putExtra("open_id", bindModel.getData().getOpen_id());
                        startActivity(intent);
                    } else {
                        Toast.makeText(LoginActivity.this, bindModel.getMessage() + "", Toast.LENGTH_SHORT).show();
                        MyPerference.getInstance().setUserInfoSave(bindModel.getData().getId(),
                                bindModel.getData().getPhone(),
                                bindModel.getData().getPassword(),
                                bindModel.getData().getIs_auth());
                    }
                    finish();
                } else {
                    Toast.makeText(LoginActivity.this, codeModel.getMessage() + "", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Object tag, Throwable e) {
                log.debug("e.getMessage() = "+e.getMessage());
                Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }

        });
    }

    private void setPosition(int position) {
        if (position == 0) {
            shareLogin.setVisibility(View.VISIBLE);
            shareRegister.setVisibility(View.GONE);
        } else {
            shareLogin.setVisibility(View.GONE);
            shareRegister.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onFragmentInteraction(Uri uri) {


    }

    class LoginOrRegisterAdapter extends FragmentPagerAdapter {
        private Context mContext;

        public LoginOrRegisterAdapter(FragmentManager fm, Context context) {
            super(fm);
            mContext = context;
        }

        @Override
        public Fragment getItem(int arg0) {
            // TODO Auto-generated method stub
            //根据fragment的包名得到对应的fragment
            return Fragment.instantiate(mContext, fragments[arg0]);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return fragments.length;
        }
    }

}
